//
//  HomeViewController.m
//  Systetagram
//
//  Created by 欧杨 on 2021/1/3.
//

#import <Masonry.h>
#import <AFNetworking.h>

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "HomeCollectionViewCell.h"
#import "UICollectionViewMultiFlowLayout.h"
#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "ImageProcessing.h"

static NSString *homeCellReuseIdentifier = @"homeCell";

@interface HomeViewController ()<UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate, UICollectionViewDataSource>

@property UIActivityIndicatorView *loading;

@end

@implementation HomeViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupImages];
    }
    return self;
}

- (void) setupSubviews
{
    [self.loading stopAnimating];
    UIButton *write = [UIButton buttonWithType: UIButtonTypeContactAdd];
    //[_write setTitle:@"发布" forState:UIControlStateNormal];
    [write addTarget:self action:@selector(openAlbum) forControlEvents:UIControlEventTouchUpInside];
    //[self.view addSubview:_write];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:write];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15, 0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.top.bottom.equalTo(self.view);
        //make.bottom.equalTo(self.view.mas_bottom).offset(-100);
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:UIColor.whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    UIImage *unselected = [[UIImage imageNamed:@"home"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImage *selected = [[UIImage imageNamed:@"home"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UITabBarItem *tabbarItem = [[UITabBarItem alloc] initWithTitle:nil image:unselected selectedImage:selected];
    self.tabBarItem = tabbarItem;
    
    UILabel *sysu = [[UILabel alloc] init];
    sysu.text = @"SYSU";
    sysu.textAlignment = NSTextAlignmentLeft;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sysu];
    
    self.loading = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.loading.center = self.view.center;
    self.loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge;
    [self.loading startAnimating];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewMultiFlowLayout *flowLayout = [[UICollectionViewMultiFlowLayout alloc] init];
        flowLayout.items = self.blogs;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.whiteColor;
        [_collectionView registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:homeCellReuseIdentifier];
    }
    return _collectionView;
}

- (void)setupImages
{
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/", myDelegate.userID, @"/hotBlog"];
    NSDictionary *header = @{@"token":myDelegate.token};
    [manager GET:URLString parameters:nil headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ok"] boolValue]) {
            self.blogs = [NSMutableArray array];
            for (NSDictionary *dic in responseObject[@"data"]) {
                [self.blogs addObject:[[blogModel alloc] initWithDictionary:dic]];
            }
            [self setupSubviews];
        } else {
            NSLog(@"something wrong when get hotblog");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (void)reload
{
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/", myDelegate.userID, @"/hotBlog"];
    NSDictionary *header = @{@"token":myDelegate.token};
    [manager GET:URLString parameters:nil headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ok"] boolValue]) {
            self.blogs = [NSMutableArray array];
            for (NSDictionary *dic in responseObject[@"data"]) {
                [self.blogs addObject:[[blogModel alloc] initWithDictionary:dic]];
            }
            [self.collectionView reloadData];
        } else {
            NSLog(@"something wrong when get hotblog");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.blogs.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:homeCellReuseIdentifier forIndexPath:indexPath];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"http://47.107.247.52:8080/", self.blogs[indexPath.item].picture];
    NSURL *imageURL = [NSURL URLWithString:url];
    NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *image = [UIImage imageWithData:data];
                [cell setBackgroundView:[[UIImageView alloc] initWithImage:image]];
                [cell configureGesture];
                cell.model = self.blogs[indexPath.item];
                cell.image = image;
            });
        }
    }];
    [task resume];
    return cell;
}

//- (UIImage *)imageWithColor:(UIColor *)color
//{
//    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextTranslateCTM(context, 0, self.size.height);
//    CGContextScaleCTM(context, 1.0, -1.0);
//    CGContextSetBlendMode(context, kCGBlendModeNormal);
//    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
//    CGContextClipToMask(context, rect, self.CGImage);
//    [color setFill];
//    CGContextFillRect(context, rect);
//    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newImage;
//}

- (void)openAlbum{
    UIImagePickerController *imagePicker= [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePicker.mediaTypes = @[(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie];
    imagePicker.allowsEditing = NO;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *img = info[@"UIImagePickerControllerOriginalImage"];
    ImageProcessing *imgProc = [[ImageProcessing alloc]init:img];
    imgProc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imgProc animated:YES completion:nil];
}

@end
